package com.hycreate.platform.common.utils;

import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

/**
 * 数据库操作工具类
 * @author hoader
 *
 */
public class DBSourceUtils {
	
	private static Logger logger = LoggerFactory.getLogger(DBSourceUtils.class);
	
	/**
	 * 保存全局属性值
	 */
	private static Map<String, String> map = Maps.newHashMap();
	
	/**
	 * 属性文件加载对象
	 */
	private static PropertiesLoader loader = new PropertiesLoader("hycreate.properties");
	
	private static String driver = getConfig("jdbc.driver");
	private static String url = getConfig("jdbc.url");
	private static String userName = getConfig("jdbc.username");
	private static String password = getConfig("jdbc.password");

	
	/**
	 * 创建数据库
	 * @param dataBaseName
	 */
	public static void createDataBase(String dataBaseName){
		try {
			Class.forName(driver).newInstance();
			Connection conn = DriverManager.getConnection(url, userName, password);
			Statement smt = conn.createStatement();
			if (conn != null) {
				logger.info("数据库连接成功！");
				String databaseSql = "CREATE database " + dataBaseName;
				smt.executeUpdate(databaseSql);
				logger.info("数据库创建完成！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("数据库创建失败！");
		}
	}
	
	/**
	 * 初始化表、数据
	 * @param sqlFileUrl 数据库初始化脚本
	 * @param dataBaseName 数据名称
	 */
	public static void initTableData(String dataBaseName, String sqlFileUrl){
		try {
			String newUrl = newDataBaseUrl(dataBaseName);
			logger.info("新数据库URL："+newUrl);
			Class.forName(driver).newInstance();
			Connection conn = (Connection) DriverManager.getConnection(newUrl, userName, password);
			ScriptRunner runner = new ScriptRunner(conn);
			runner.setErrorLogWriter(null);
			runner.setLogWriter(null);
			
			logger.error("表、数据初始化开始！");
//			runner.runScript(Resources.getResourceAsReader("userfiles/1/files/project/tbProject/2016/11/pms.sql"));
			runner.runScript(Resources.getUrlAsReader(sqlFileUrl));
			logger.error("表、数据初始化成功！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("表、数据初始化失败！");
		}
	}
	
	/**
	 * 获取初始化脚本地址
	 * @param sqlFileUrl
	 * @return
	 */
	public static String getFilePath(String sqlFileUrl){
		String s = DBSourceUtils.class.getClassLoader().getResource("").getPath();
		String r = s.split("WEB-INF")[0];
		String result = r.substring(1, r.length())+"userfiles"+sqlFileUrl.split("userfiles")[1];
		System.out.println(result);
		
	    URL url;
		try {
			url = new URL(sqlFileUrl);
			URLConnection conn = url.openConnection();
			conn.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
	    
		return result;
	}
	
	/**
	 * 获取配置
	 * 
	 */
	public static String getConfig(String key) {
		String value = map.get(key);
		if (value == null){
			value = loader.getProperty(key);
			map.put(key, value != null ? value : StringUtils.EMPTY);
		}
		return value;
	}
	
	/**
	 * 初始化数据库
	 * @param dataBaseName 数据库名称
	 * @param sqlFileUrl 初始化脚本URL
	 */
	public static void initDataBase(String dataBaseName, String sqlFileUrl){
		createDataBase(dataBaseName);
		initTableData(dataBaseName, sqlFileUrl);
	}
	
	/**
	 * 获取新数据库URL
	 * @param dataBaseName
	 * @return
	 */
	public static String newDataBaseUrl(String dataBaseName){
		String s = url.split("[?]")[0];
		String[] r = s.split("/");
		String i = r[r.length-1];
		return url.replaceFirst(i, dataBaseName);
	}
	
	
	public static void main(String[] args) {
		String t = "jdbc:mysql://192.168.0.8:3306/pms?useUnicode=true&characterEncoding=utf-8";
		String s = t.split("[?]")[0];
		String[] r = s.split("/");
		String i = r[r.length-1];
		System.out.println(t.replaceFirst(i, "tttttt"));
	}
}
